import axios from 'axios';

const api = axios.create({
  baseURL: '/api', // 恢复/api前缀以便代理识别
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json'
  }
});

// 请求拦截器 - 使用api实例
api.interceptors.request.use(
  (config) => {
    // 增强请求日志
    const fullUrl = config.baseURL + config.url;
    console.log(`[请求] ${config.method.toUpperCase()} ${fullUrl}`);
    console.log('请求参数:', config.data);
    console.log('请求头:', config.headers);
    const token = localStorage.getItem('token');
    if (token && token.trim() !== '') {
      config.headers.authorization = `${token}`;
    }
    return config;
  },
  (error) => {
    console.error('请求拦截器错误:', error);
    return Promise.reject(error);
  }
);

// 响应拦截器 - 使用api实例
api.interceptors.response.use(
  (response) => {
    console.log('响应数据:', response.data);
    if (typeof response.data === 'object' && 'code' in response.data) {
      return response.data;
    }
    return {
      code: response?.code || 200,
      data: response.data,
      msg: response?.msg || ''
    };
  },
  (error) => {
    // 增强错误日志
    const errorUrl = error.config?.baseURL + error.config?.url;
    console.error(`[错误] ${error.config?.method.toUpperCase()} ${errorUrl} (${error.response?.status || '无响应'})`);
    console.error('完整错误响应数据:', JSON.stringify(error.response?.data, null, 2));
    console.error('后端验证错误详情:', JSON.stringify(error.response?.data?.errors || error.response?.data?.message || '无具体错误信息', null, 2));
    console.error('错误响应头:', error.response?.headers);
    console.error('错误详情:', error.message);
    const response = error.response;
    return Promise.reject({
      code: response?.status || -1,
      data: response?.data || null,
      msg: response?.data?.msg || '请求失败'
    });
  }
);



// 在文件末尾添加
export const auditUser = (auditDTO) => {
  return api.post('/admin/AuditUser', auditDTO);
};
// 新增API函数定义和导出
// 获取维修任务列表
export const getMyRepair = (params) => {
  return api.get('/users/getMyRepair', { params });
};

// 获取已完成的维修订单
export const getMyCompletedRepair = (params) => {
  return api.get('/users/getMyCompletedRepair', { params });
};

// 完成维修单
export const completeRepair = (data) => {
  return api.post('/user/completeRepair', data);
};

// 修改维修单状态 (保持不变，用于开始维修)
export const changeRepairStatus = (params) => {
  return api.get('/users/changeRepairStatus', { params });
};

// 添加维修计划API接口
export const getMyMaintenanceSchedules = (params) => {
  return api.get('/users/getMyMaintenanceSchedules', { params });
};

// 添加日常维护报告接口
export const getMyDailyMaintenance = (params) => {
  return api.get('/users/getMyDailyMaintenance', { params });
};

// 新增：提交日常维护日志接口
export const submitDailyLog = (data) => {
  return api.post('/users/submitDailyLog', data);
};

export default api;
